package com.bmobxiaowa.activity.file;

import han.k.base.BaseActivity;
import han.k.view.K_TopBar;
import han.k.view.K_TopBar.TopBarClickListener;

import java.util.List;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.Display;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

import com.bmobxiaowa.R;
import com.bmobxiaowa.fragment.photo.PhotoFolderFragment;
import com.bmobxiaowa.fragment.photo.PhotoFragment;
import com.bmobxiaowa.fragment.photo.PhotoInfo;

public class FileChooserActivity extends BaseActivity {

	private int backInt = 0;
	private List<PhotoInfo> selectPhotoData;// 选择的数据

	protected void onCreate(Bundle savedInstanceState) {
		EventBus.getDefault().register(this);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.filechooser_show);
		rchangeFragments(R.id.bodys, new PhotoFolderFragment());
		K_TopBar topbar = (K_TopBar) findViewById(R.id.topbars);
		topbar.setOnTopBarClickListener(new TopBarClickListener() {
			// 点击完成选择
			@Override
			public void rightClick() {
				if (selectPhotoData==null ||selectPhotoData.size() == 0) {
					toast_("请选择图片");
				}else{
					EventBus.getDefault().post(selectPhotoData,"selectPhotoData");
					FileChooserActivity.this.finish();
				}
			}
			// 点击返回按钮
			@Override
			public void leftClick() {
				if (backInt == 1) {
					FileChooserActivity.this.finish();
				} else {
					backInt--;
					getSupportFragmentManager().popBackStack();
				}
			}
		});

	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		WindowManager m = getWindowManager();
		Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高
		LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
		p.height = (int) (d.getHeight() * 0.8); // 高度设置为屏幕的1.0
		p.width = (int) (d.getWidth() * 0.85); // 宽度设置为屏幕的0.8
		getWindow().setAttributes(p);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}

	// 接收到所点击的选择的图片文件夹的所有图片
	@Subscriber
	public void itemPhotoData(List<PhotoInfo> data) {
		rchangeFragments(R.id.bodys, PhotoFragment.newInstance(data));
	}

	// 接收到选择的图片
	@Subscriber(tag = "selectPhoto")
	public void selectPhotoData(List<PhotoInfo> data) {

		selectPhotoData = data;
	}

	/**
	 * 添加带回退栈的
	 * 
	 * @param resView
	 * @param targetFragment
	 */
	public void rchangeFragments(int resView, Fragment targetFragment) {
		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		transaction.replace(resView, targetFragment, targetFragment.getClass()
				.getName());
		transaction.addToBackStack(null);
		transaction.commit();
		backInt++;
	}

}